﻿using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.IO;
using System.Threading;
using System.ComponentModel;
using System.Collections.Generic;
using System.Reflection;

namespace PictureResizerForms
{
    public partial class frm_Main : Form
    {
        private GlobalSettings _MyGlobalSettings;
        private DataTable _dtTemplates;
        private Form _configForm;
        private BackgroundWorker _bgWorker;

        public frm_Main()
        {
            InitializeComponent();

            init();

            //1. Programmstart
            if (Properties.Settings.Default.TemplateFilePath.Equals("INIT"))
            {
                Properties.Settings.Default.TemplateFilePath = Path.GetDirectoryName(Application.ExecutablePath) + "\\Templates.xml";
            }
            //-------------------

            _MyGlobalSettings = new GlobalSettings();
            _dtTemplates = _MyGlobalSettings.Templates().dt;
            this.RefreshTemplateSelector();
        }

        private void init()
        {
            btn_abort.Enabled = false;

            string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            this.Text = String.Format("Picture Resizer V.{0}", version);

        }


        private void frm_Main_Load(object sender, EventArgs e)
        {
            _bgWorker = new BackgroundWorker();
            _bgWorker.WorkerReportsProgress = true;
            _bgWorker.WorkerSupportsCancellation = true;
            _bgWorker.DoWork += new DoWorkEventHandler(worker_DoWork);
            _bgWorker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            _bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            toolStripProgressBar1.Value = 0;
            toolStripProgressBar1.Maximum = 0;

            list_Pictures.Clear();

            btn_start.Enabled = true;
            btn_abort.Enabled = false;
        }

        private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            toolStripProgressBar1.Value++;
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            WorkObject wo = (WorkObject)e.Argument;

            if (!(wo.ActualSettings == null))
            {
                //Falls OutputPath nicht existiert, erstellen
                if (!Directory.Exists(wo.ActualSettings.outputPath))
                    Directory.CreateDirectory(wo.ActualSettings.outputPath);

                String filename;
                String path;
                Image image, newImage;
                PictureResize pr = new PictureResize();

                foreach (String file in wo.files)
                {
                    if ((_bgWorker.CancellationPending == true))
                    {
                        e.Cancel = true;
                        break;
                    }
                    else
                    {
                        path = file.ToString();
                        filename = Path.GetFileName(path);

                        try
                        {
                            image = Image.FromFile(path);
                            newImage = pr.ScaleImage(image, Int32.Parse(wo.ActualSettings.height), Int32.Parse(wo.ActualSettings.width));

                            newImage.Save(wo.ActualSettings.outputPath + filename, ImageFormat.Jpeg);

                            image.Dispose();
                            newImage.Dispose();
                        }
                        catch (OutOfMemoryException oom)
                        {
                            System.Console.WriteLine("File was no Image.");
                            String message = String.Format("{0} ist kein Bild.", filename);
                            MessageBox.Show(message,"Fehler");
                        }

                        _bgWorker.ReportProgress(0);
                    }

                }

                
            }

            wo = null;
        }
        

        public void RefreshTemplateSelector()
        {
            cbox_Template.DataSource = _MyGlobalSettings.Templates().GetTemplatesList();
        }

        private void beendenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void einstellungenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _configForm = new frm_Config();
            _configForm.Show();
            _configForm.FormClosed += new FormClosedEventHandler(configForm_FormClosed);
        }

        void configForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.RefreshTemplateSelector();
            _configForm.Dispose();
        }

        private void list_Pictures_DragDrop(object sender, DragEventArgs e)
        {
            toolStripProgressBar1.Maximum = 0;

            // Extract the data from the DataObject-Container into a string list
            string[] FileList = (string[])e.Data.GetData(DataFormats.FileDrop, false);

            // For example add all files into a simple label control:
            foreach (string File in FileList)
            {
                if (File.EndsWith(".jpg") || File.EndsWith(".JPG"))
                {
                    list_Pictures.Items.Add(File);
                    toolStripProgressBar1.Maximum++;
                }
            }

            FileList = null;
        }

        private void list_Pictures_DragEnter(object sender, DragEventArgs e)
        {
            // Check if the Dataformat of the data can be accepted
            // (we only accept file drops from Explorer, etc.)
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy; // Okay
            else
                e.Effect = DragDropEffects.None; // Unknown data, ignore it
        }

        private void btn_start_Click(object sender, EventArgs e)
        {
            btn_start.Enabled = false;
            btn_abort.Enabled = true;

            WorkObject wo = new WorkObject();
            wo.ActualSettings = _MyGlobalSettings.Templates().getSettings(cbox_Template.Text.ToString());

            List<String> files = new List<String>();

            foreach (ListViewItem file in list_Pictures.Items)
            {
                files.Add(file.Text.ToString());
            }

            wo.files = files;
            toolStripProgressBar1.Value = 0;

            _bgWorker.RunWorkerAsync(wo);

            files = null;
            wo = null;
        }

        private void überToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new AboutBox().Show();
        }

        private void bt_abort_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Aktuellen Vorgang abbrechen?", "Abbruch", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                _bgWorker.CancelAsync();
                btn_start.Enabled = true;
                btn_abort.Enabled = false;
            }
        }

        private void list_Pictures_KeyPress(object sender, KeyPressEventArgs e)
        {
           
        }

        private void list_Pictures_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                ListView.SelectedListViewItemCollection selection = list_Pictures.SelectedItems;

                foreach (ListViewItem item in selection)
                {
                    list_Pictures.Items.Remove(item);
                }

            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Liste leeren?", "Liste leeren", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                list_Pictures.Items.Clear();
            }
        }

    }
}
